/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.sound.filter;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class FilteredSoundStream extends FilterInputStream {
    
    private static final int REAMINING_SIZE_UNKOWN = -1;
    
    private SoundFilter soundFilter;
    private int         remainingSize;
    
    public FilteredSoundStream(InputStream in, SoundFilter soundFilter) {
        super(in);
        this.soundFilter = soundFilter;
        this.remainingSize = REAMINING_SIZE_UNKOWN;
    }

    @Override
    public int read(byte[] buffer, int offset, int lenght) throws IOException {
        int bytesRead = super.read(buffer, offset, lenght);
        if( bytesRead > 0 ) {
            soundFilter.filter(buffer, offset, bytesRead);
            return bytesRead;
        }
        if( remainingSize == REAMINING_SIZE_UNKOWN ) {
            remainingSize = soundFilter.getRemainingSize();
            remainingSize = remainingSize / 4 * 4;
        }
        if( remainingSize > 0 ) {
            lenght = Math.min(lenght,remainingSize);
            for(int i=offset;i<offset+lenght;i++) {
                buffer[i] = 0;
            }
            // filter remaining bytes...
            soundFilter.filter(buffer, offset, lenght);
            remainingSize -= lenght;
            // return
            return lenght;
        } else {
            // end of stream
            return -1;
        }
    }
    
}
